package main

import (
	"common/log"
	"context"
	"errors"
	"euplink"
	"fmt"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"os"
	"path"
	"time"
)

var downladHlsCmd = &cobra.Command{
	Use:   "downloadhls",
	Short: "下载hls",
	Long:  "euplink downloadhls (local_src) dir_save",
	RunE:  cmdDownloadHls,
}

func cmdDownloadHls(cmd *cobra.Command, args []string) error {
	if len(args) != 2 {
		return errors.New("参数错误")
	}

	var saveDir = args[1]

	ctx := context.Background()
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(ctx)
	defer cancel()
	zapLog := log.NewZapLog(&runConfig.Log)
	//runConfig.Project.LocalDeviceId = runConfig.LocalDeviceId
	//runConfig.Project.RootKey = rootKeyToMd5(runConfig.RootKey)
	//runConfig.Project.ApiKey = runConfig.ApiKey

	files, err := parseM3u8File(args[0])
	if err != nil {
		zapLog.Error("parseM3u8File failed", zap.Error(err))
		return nil
	}

	prj, err := euplink.NewProject(ctx, runConfig.Project, zapLog)
	if err != nil {
		return fmt.Errorf("project init err: %s", err)
	}
	//prj.StartUpdateNodeServer(ctx)

	//dir, _ := path.Split(args[0])
	var success, failed int
	var count = len(files)
	for i := 0; i < count; {
		var file = files[i]
		localFile := path.Join(saveDir, file)
		fmt.Println("download ", file, " to ", localFile)
		outFile, err := os.OpenFile(localFile, os.O_WRONLY|os.O_CREATE, os.ModePerm)
		if err != nil {
			fmt.Println("download:create file: ", file, " err: ", err)
		}
		t1 := time.Now()
		ctx2 := context.Background()
		err = prj.DownloadObject(ctx2, runConfig.Project.DefaultBucket, file, outFile)
		if err != nil {
			outFile.Close()
			failed++
			zapLog.Error("下载失败", zap.String("file", file), zap.Error(err))
			time.Sleep(time.Second * 3)
			break
		} else {
			outFile.Close()
			i++
			success++
			zapLog.Info("下载成功", zap.String("file", file), zap.Duration("time", time.Now().Sub(t1)))
		}
		zapLog.Info("统计:", zap.Int("failed", failed), zap.Int("success", success))

	}
	return nil
}
